package com.pay.service.impl;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.pay.common.util.PropertyUtil;
import com.pay.common.util.StringUtil;
import com.pay.constants.ExpriseTimeConstants;
import com.pay.constants.RedisKeyConstants;
import com.pay.constants.WeixinConstants;
import com.pay.dubbo.wx.WxServiceFacade;
import com.pay.service.AccessTokenService;
import com.pay.util.RedisUtil;

@Service("accessTokenService")
public class AccessTokenServiceImpl implements AccessTokenService {
	private Log log = LogFactory.getLog(AccessTokenServiceImpl.class);
	@Resource
	private WxServiceFacade wxServiceFacade;
	private static String ysappid;
	private static String ysAppsecret;
	static {
		PropertyUtil propertyUtil = PropertyUtil.getInstance("wxweb");
		ysappid = propertyUtil.getProperty("ysAppid");
		ysAppsecret = propertyUtil.getProperty("ysAppsecret");
	}

	@Override
	public String getAccessToken() {
		String accessToken = RedisUtil.getValue(RedisKeyConstants.KY_ACCESS_TOKEN);
		log.info("获取token服务：accessTokenService accessTokenredis = " + accessToken);

		if (accessToken == null) {
			String accessTokenJson = wxServiceFacade.getAccessToken(ysappid, ysAppsecret);
			log.info("accessTokenService accessTokenJson = " + accessTokenJson);
			JSONObject obj = JSON.parseObject(accessTokenJson);

			accessToken = (String) obj.get("access_token");

			if (StringUtil.notNull(accessToken)) {
				log.info("accessTokenService accessToken = " + accessToken);
			} else {
				log.info("accessTokenService accessToken为空，错误原因：" + accessTokenJson);
			}

			RedisUtil.setKeyValue(RedisKeyConstants.KY_ACCESS_TOKEN, accessToken,
					ExpriseTimeConstants.expriseTime3600);
		}
		return accessToken;
	}
	

	@Override
	public String getApiTicket() {
		String apiTicket = RedisUtil.getValue(RedisKeyConstants.KY_API_TICKET);
		String accessToken = getAccessToken();
		log.info("accessTokenService accessToken = " + accessToken);
		if (apiTicket == null) {
			String apiTicketJson = wxServiceFacade.getApiTicket(accessToken);
			log.info("accessTokenService getApiTicket = " + apiTicketJson);
			if (!StringUtils.isEmpty(apiTicketJson)) {
				JSONObject parseObject = JSON.parseObject(apiTicketJson);
				if (parseObject.containsKey("errmsg")) {
					String errmsg = (String) parseObject.get("errmsg");
					if (errmsg.equals("ok")) {
						String ticket = (String) parseObject.get("ticket");
						apiTicket = ticket;
						log.info("accessTokenService apiTicket = " + ticket);
						RedisUtil.setKeyValue(RedisKeyConstants.KY_API_TICKET, ticket,
								ExpriseTimeConstants.expriseTime3600);
					}
				}
			}
		}
		return apiTicket;
	}

}
